package cn.caplike.demo.nio._2021.channel;

import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * Description:
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2021-12-21 13:29
 */
public class NioFromIo {

    public static void main(String[] args) throws IOException {
        input();
        output();
    }

    private static void input() throws IOException {
        final URL resource = NioFromIo.class.getResource("/data/nio-from-io-read.txt");
        assert resource != null;

        FileInputStream inputStream = new FileInputStream(resource.getPath());
        FileChannel fileChannel = inputStream.getChannel(); // !

        ByteBuffer buffer = ByteBuffer.allocate(512); // 512 底层数组的大小
        fileChannel.read(buffer);

        buffer.flip();
        while (buffer.remaining() > 0) {
            byte[] innerBuffer = new byte[2];
            buffer = buffer.get(innerBuffer);
            System.out.println("Character: " + new String(innerBuffer, StandardCharsets.UTF_8.name()));
        }

        inputStream.close();
    }

    private static void output() throws IOException {
        final URL resource = NioFromIo.class.getResource("/data/nio-from-io-write.txt");
        assert resource != null;

        FileOutputStream outputStream = new FileOutputStream(resource.getPath());
        FileChannel fileChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(512);
        byte[] message = "一二三四5".getBytes(StandardCharsets.UTF_8);
        for (byte b : message) {
            buffer.put(b);
        }

        buffer.flip();
        fileChannel.write(buffer);
        outputStream.close();
    }
}
